<template>
    <div class="voteMain">
        <div class="voteTop">
            <el-button @click="addVote" class="adBtn">新增</el-button>
            <div class="timeBox">
                <el-statistic format="mm:ss.SSS" v-if="timeFlag" :value="deadline" ref="countDownModule"
                    @finish="finishHandle" time-indices>
                </el-statistic>
                <div class="timeStr" v-else>{{ timeStr }}</div>
            </div>
            <div class="erCode">
                <img :src="form.signaturePic" alt="" srcset="">
            </div>

            <div class="startBtn" @click="startHandle">{{ finishFlag ? '继续投票' : '开始投票' }}</div>
        </div>

        <template v-if="voteList.length != 0">
            <div class="voteTit">
                <span>投票选项</span>
                <span>获取票数</span>
            </div>
            <div class="voteList">
                <div class="voteItem" v-for="(item, index) in voteList" :key="index">
                    <img class="yuanImg" src="../assets/X2/index/yuan.png" alt="圆">
                    <div>
                        <span class="voteItemTit">{{ item.voteItem }}</span>
                        <div class="voteItemContent">
                            <el-progress :percentage="item.pressNum" class="line" text-color="#513462"></el-progress>
                        </div>
                    </div>
                    <div>
                        <span>{{ item.voteNum }}</span>票
                    </div>
                </div>
            </div>
        </template>

        <div class="emptyBox" v-else>
            <div class="empTit">
                暂未设置投票项
            </div>
        </div>

        <el-dialog title="设置投票项" :visible.sync="addFlag" width="30%" :before-close="closeAddHandle">
            <el-form ref="form" :model="voteForm" label-width="80px">
                <el-form-item label="投票项">
                    <el-input type="textarea" :rows="4" v-model="voteForm.content" placeholder="请输入投票项"></el-input>
                    <div>*每个投票项之间请使用@进行分割</div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddHandle">取 消</el-button>
                <el-button type="primary" @click="addSubmitHandle">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>



<script>
import { addVoteItem, listCurrentVote } from "../network/vote";
export default {
    name: 'vote',
    data() {
        return {
            addFlag: false,
            vote: '',
            voteList: [],
            voteForm: {
                content: '',
            },
            totalNum: 0.5, //几百
            timeStr: "",
            timeFlag: false,
            // 倒计时
            deadline: 0,
            time: 1,
            finishFlag: false,
            startFlag: false,
            form: {},
        }
    },
    created() {
        this.timeStr = `0${this.time}:00:000`;
        if (localStorage.form != undefined) {
            this.form = JSON.parse(localStorage.form)
            console.log(this.form);
        }

        console.log(this.timeStamp);
        this.getData()

        // setTimeout(() => {
        //     this.socket.close();
        // }, 2000);
    },
    methods: {

        getData() {
            listCurrentVote({
                actId: this.form.signatureId
            }).then(res => {
                if (res.flag) {
                    this.voteList = res.data
                    var arr = localStorage.voteList == undefined ? [] : JSON.parse(localStorage.voteList)
                    console.log(arr);
                    console.log(this.voteList);
                    this.voteList.forEach(ele => {
                        ele.voteNum = 0
                        ele.pressNum = 0
                        arr.forEach(item => {
                            if (ele.voteId == item.voteId) {
                                ele.voteNum = item.voteNum
                                ele.pressNum = item.pressNum
                            }
                        })
                    })
                    this.dataHandle();
                }
            })
        },
        addVote() {
            this.addFlag = true
        },
        // 添加 投票项  确认
        addSubmitHandle() {
            if (this.voteForm.content == '') {
                this.$message.warning('请输入投票内容')
                return
            }
            addVoteItem({
                itemList: this.voteForm.content,
                actId: this.form.signatureId,
                times: new Date().getTime(),
            }).then(res => {
                if (res.flag) {
                    console.log(res.data);
                    this.voteList = res.data
                    this.voteList.forEach(ele => {
                        ele.voteNum = 0
                        ele.pressNum = 0
                    })
                    this.timeFlag = false;
                    this.startFlag = false
                    this.finishFlag = false
                }
            })
            this.timeStr = `0${this.time}:00:000`;
            this.closeAddHandle()
        },
        // 添加投票项 关闭
        closeAddHandle() {
            this.addFlag = false
        },
        dataHandle() {
            console.log(this.voteList);
            this.voteList.forEach((ele) => {
                ele.pressNum = Math.ceil(ele.voteNum / this.totalNum);
                ele.pressNum = ele.pressNum > 100 ? 100 : ele.pressNum;
            });
            console.log(this.voteList);
            this.voteList = this.voteList.sort((a, b) => {
                return b.voteNum - a.voteNum
            })
            this.$forceUpdate()
        },
        // 开始投票 开始倒计时
        startHandle() {
            if (this.startFlag) {
                this.$message.warning('投票已开始，请勿重复点击')
                return
            }
            if (this.voteList.length == 0) {
                this.$message.warning('请设置投票项')
                return
            }
            if (!this.finishFlag) {
                this.timeFlag = true;
                var num = 1000 * 60 * (this.time * 1);
                this.deadline = Date.now() + num;
                this.startFlag = true
                this.openWeb()
            } else {
                this.timeStr = `0${this.time}:00:000`;
                this.voteList = []
                this.voteForm.content = ''
                this.addFlag = true
                this.timeFlag = false;
                this.startFlag = false
                this.finishFlag = false
            }
        },
        // 倒计时结束
        finishHandle() {
            this.$message.success('投票结束，请查看投票结果')
            this.finishFlag = true
            this.startFlag = false
            this.socket.close();
        },
        openWeb() {
            if (typeof WebSocket == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                // var socketUrl = "http://192.168.0.111:2033/imserver/" + 'v_' + this.form.signatureId;
                var socketUrl = "wss://www.ccclkj.cn:2033/imserver/" + 'v_' + this.form.signatureId;
                socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
                console.log(socketUrl);
                if (this.socket != null) {
                    this.socket.close();
                    this.socket = null;
                }
                //打开事件
                this.socket = new WebSocket(socketUrl);
                //打开事件
                this.socket.onopen = function () {
                    console.log("websocket已打开");
                };
                var _this = this;
                //获得消息事件
                _this.socket.onmessage = function (msg) {
                    console.log(msg.data);
                    if (msg.data == "连接成功") {
                        _this.$message({
                            type: "success",
                            duration: 500,
                            offset: "400",
                            message: "连接成功",
                        });
                    }
                    if (msg.data != "连接成功") {
                        var data = JSON.parse(msg.data);
                        console.log(data);
                        console.log(_this.finishFlag);
                        if (!_this.finishFlag) {
                            var idArr = data.itemIds.split(",");
                            console.log(idArr);
                            var arr = _this.voteList;
                            arr.forEach((ele) => {
                                idArr.forEach((item) => {
                                    if (ele.voteId == item) {
                                        ele.voteNum++;
                                    }
                                });
                            });
                            localStorage.voteList = JSON.stringify(arr)
                            _this.voteList = arr
                            _this.dataHandle();
                        }
                    }
                };
                //关闭事件
                this.socket.onclose = function () {
                    _this.$message.warning("投票通道已关闭");
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                this.socket.onerror = function () {
                    _this.$message.warning("连接失败");
                    console.log("websocket发生了错误");
                };
            }
            console.log(_this.userList);
        },
    },

}
</script>

<style lang="less" scoped>
.voteMain {
    padding-top: 20px;

    .voteTop {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        padding: 0 48px 20px;
        font-size: 24px;
        font-family: Source Han Sans CN;
        font-weight: bold;
        color: #0B1532;
        border-bottom: 2px solid #F2F2F2;
        cursor: pointer;
    }

    // .startBtn {
    //     position: absolute;
    //     bottom: 20px;
    //     right: 48px;
    //     z-index: 10;
    // }
    // .adBtn{
    //     z-index: 10;
    // }

    .voteTit {
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 16px 175px 16px 110px;
        width: 100%;
        border-bottom: 2px solid #F2F2F2;
        font-size: 24px;
        font-family: Source Han Sans CN;
        font-weight: bold;
        color: #0B1532;

        span {
            cursor: pointer;
        }
    }

    .voteList {
        width: 100%;
        height: 700px;
        overflow-y: scroll;

        .voteItem {
            position: relative;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 174px 20px 110px;
            border-bottom: 2px solid #F2F2F2;

            .yuanImg {
                position: absolute;
                top: 22px;
                left: 46px;
            }

            >div {
                .voteItemTit {
                    font-size: 28px;
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    color: #333333;
                    cursor: pointer;
                }

                .voteItemContent {
                    margin-top: 27px;
                    width: 1400px;
                }
            }

            >div:last-child {
                font-size: 16px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                color: #333333;

                span {
                    margin-right: 80px;
                    font-size: 38px;
                    font-family: Source Han Sans CN;
                    font-weight: bold;
                    color: #3E68FF;
                }
            }
        }

        .voteItem:last-child {
            border-bottom: none;
        }
    }

    ::-webkit-scrollbar {
        display: none;
    }

}


.line {
    width: 100;
    height: 40px;
    background: #513462;
    border-radius: 29px 34px 34px 29px;
}

/deep/ .el-progress-bar__outer {
    height: 40px !important;
    background: transparent !important;
    border: none !important;
    border-radius: 29px 34px 34px 29px !important;
}

/deep/.el-progress-bar__inner {
    background: linear-gradient(212deg, #fed98b 0%, #cc904a 100%) !important;
    border-radius: 29px 34px 34px 29px !important;
}

/deep/.el-progress-bar {
    width: 450px !important;
    padding-right: 0px !important;
    // background-color: #C6D3E2;
}


.timeBox {
    width: 40%;
    height: 66px;
    text-align: center;
    background-color: #c6d3e2;
    font-size: 60px;
    font-weight: 400;
    background: linear-gradient(15deg, #d29e64 0%, #ffe2a6 50%, #d29e64 100%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-family: "字体1";
    color: transparent;
    z-index: 1;
}

.el-statistic,
.el-statistic .con /deep/ .number {
    font-size: 60px !important;
}

.el-statistic /deep/ .con .number {
    font-size: 60px !important;
    font-family: "字体1" !important;
}

.emptyBox {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 70vh;
}

.empTit {
    font-size: 60px;
    color: #666;
    cursor: pointer;
}

.erCode {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 180px;
    top: -20px;
    // width: 140px;
    // height: 140px;
    font-size: 20px !important;
    color: #0B1532 !important;
    font-weight: bold !important;
}

.erCode>img {
    margin-bottom: 6px !important;
    width: 100px !important;
    height: 100px !important;
    // background: #EBF0FF;
    border-radius: 10px !important;
}
</style>